﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Configuration;
using System.Diagnostics;
using System.Threading;
using System.Web;

namespace BuildSiteTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        List<String> PicExtList = new List<string> { ".png", ".jpg", ".gif", ".jpeg", ".webp", ".bmp" };

        /// <summary>
        /// 默认文档目录
        /// </summary>
        public String DefaultPath
        {
            get { return ConfigurationManager.AppSettings["defaultPath"]; }
            set
            {
                Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                cfa.AppSettings.Settings["defaultPath"].Value = value;
                cfa.Save();
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            txtDir.Text = DefaultPath;
        }
        /// <summary>
        /// 选择文件夹
        /// </summary>
        String getFileDir()
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文档所在文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    System.Windows.MessageBox.Show(this, "文件夹路径不能为空", "提示");
                }
                return dialog.SelectedPath + "/";
            }
            return "";
        }


        private void btSelDir_Click(object sender, RoutedEventArgs e)
        {
            path = getFileDir();
            txtDir.Text = path;
            //DefaultPath = path;
            if (path != "")
            {
                getFileList(path);
            }

        }

        /// <summary>
        /// 获取文档列表
        /// </summary>
        /// <param name="path"></param>
        void getFileList(String path)
        {
            //String[] files = Directory.GetFiles(path, "*.*");
            //排序
            //List<string> orderFiles = files.OrderBy(ss => new FileInfo(ss).LastWriteTime).ToList();


            FileInfo[] arrFi = new DirectoryInfo(path).GetFiles("*.*");
            SortAsFileLastWriteTime(ref arrFi);

            lsFile.Items.Clear();
            foreach (var file in arrFi)
            {
                String name = System.IO.Path.GetFileName(file.Name);
                //跳过图片
                if (isPicFile(name))
                {
                    continue;
                }
                //排除临时文件
                if (name.ToCharArray()[0] != '~')
                {
                    lsFile.Items.Add(name);
                }
            }
        }

        /// <summary>
        /// C#按创建时间排序（倒序）
        /// </summary>
        /// <param name="arrFi">待排序数组</param>
        private void SortAsFileLastWriteTime(ref FileInfo[] arrFi)
        {
            Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return y.LastWriteTime.CompareTo(x.LastWriteTime); });
        }

        private void btGetList_Click(object sender, RoutedEventArgs e)
        {
            path = txtDir.Text;
            if (path != "")
            {
                getFileList(path);
            }
        }

        private String _path = String.Empty;
        /// <summary>
        /// 文档目录
        /// </summary>
        public String path
        {
            get
            {
                if (_path == String.Empty)
                {
                    _path = txtDir.Text;
                }
                return _path;
            }
            set { _path = value; }
        }

        private String _rootPath = String.Empty;
        /// <summary>
        /// 网站目录
        /// </summary>
        public String rootPath
        {
            get
            {
                if (_rootPath == String.Empty)
                {
                    _rootPath = path + "../";
                }
                return _rootPath;
            }
            set { _rootPath = value; }
        }

        private String _domain = String.Empty;
        /// <summary>
        /// 网站
        /// </summary>
        public String domain
        {
            get
            {
                if (_domain == String.Empty)
                {
                    _domain = File.ReadAllText(rootPath + "tool/domain.ini");
                }
                return _domain;
            }
            set { _domain = value; }
        }


        private String _indexFile = String.Empty;
        public String indexFile
        {
            get
            {
                if (_indexFile == String.Empty)
                {
                    _indexFile = rootPath + "index.html";
                }
                return _indexFile;
            }
            set { _indexFile = value; }
        }


        private void btBuild_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String TempItem= File.ReadAllText(rootPath + "tool/TempItem.html");
                String TempMain = File.ReadAllText(rootPath + "tool/TempMain.html");
                //System.Windows.MessageBox.Show(domain);

                //项模板生成项标签
                String itemValue = "";
                foreach (String item in lsFile.Items)
                {
                    string time = (new FileInfo(path + item)).LastWriteTime.GetDateTimeFormats('f')[0].ToString();
                    itemValue += string.Format(TempItem
                        , getFileLink(item, item, time)
                        , item
                        , time
                        , getDocPic(item)
                        );
                }

                //项标签合成到页面中并保存
                File.WriteAllText(indexFile, TempMain.Replace("{0}", itemValue));
                System.Windows.MessageBox.Show("完成");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// pdf过滤
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        String getFileLink(String filename,String h1,String h2)
        {
            String ext = System.IO.Path.GetExtension(filename);
            if (ext != ".pdf")
            {
                return "item.html?file=" + System.Web.HttpUtility.UrlEncode(domain + "/file/" + filename, System.Text.Encoding.UTF8)+"&h1=" + HttpUtility.UrlEncode(h1) + "&h2=" + HttpUtility.UrlEncode(h2);
            }
            else
            {
                return domain + "/file/" + filename;
            }
        }

        /// <summary>
        /// 判断文件是否图片格式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        Boolean isPicFile(String filename)
        {
            String ext = System.IO.Path.GetExtension(filename);
            foreach (String item in PicExtList)
            {
                if (ext == item)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取对应特色图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        String getDocPic(String filename)
        {
            String docName = System.IO.Path.GetFileNameWithoutExtension(filename);
            foreach (String ext in PicExtList)
            {
                String PicName = docName + ext;
                if (File.Exists(path + PicName))
                {
                    return "file/" + PicName;
                }
            }
            return "50w.jpg";
        }


        private void btOpen_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(indexFile);
        }

        private void btGit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Process p = new Process();
                //设定调用的程序名，不是系统目录的需要完整路径   
                p.StartInfo.FileName = rootPath + "tool/"+"build.exe";
                p.StartInfo.WorkingDirectory=rootPath;
                //传入执行参数   
                p.StartInfo.Arguments = "./tool/"+"gitPush.php";
                p.StartInfo.UseShellExecute = false;
                //是否重定向标准输入   
                p.StartInfo.RedirectStandardInput = false;
                //是否重定向标准转出   
                p.StartInfo.RedirectStandardOutput = false;//是否重定向错误   
                p.StartInfo.RedirectStandardError = false;//执行时是不是显示窗口   
                p.StartInfo.CreateNoWindow = true;//启动   
                p.Start();
                //Thread.Sleep(1000);
                p.WaitForExit();
                p.Close();
                System.Windows.MessageBox.Show("完成");
            }
            catch (Exception)
            {
                System.Windows.MessageBox.Show("执行命令失败，请检查输入的命令是否正确！");
            }

        }

        private void btOpenSite_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(domain);
        }

        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DefaultPath = path;
        }
    }
}
